﻿using FarmSmartSleep.Common.Domain;
using FarmSmartSleep.Common.Domain.RBACFile;
using FarmSmartSleep.Common.Dtos;
using FarmSmartSleep.Common.Infrastructure;
using MediatR;
using Microsoft.EntityFrameworkCore;
using System.Diagnostics.Eventing.Reader;

namespace R.FarmSmartSleep.RBAC.API.Apliction.Command
{
    public class EmployeeListHandler:IRequestHandler<EmployeeListCommon,ResultPage<Employee>>
    {
        private readonly IBaseRepository<Employee> employeeRep;

        public EmployeeListHandler(IBaseRepository<Employee> employeeRep)
        {
            this.employeeRep = employeeRep;
        }

        public async Task<ResultPage<Employee>> Handle(EmployeeListCommon request, CancellationToken cancellationToken)
        {
            var result = new ResultPage<Employee>() { Code = (int)CodeEnum.search };
            try
            {
                var list = await employeeRep.GetAll().ToListAsync();
                if(!string.IsNullOrEmpty(request.FirstName))
                {
                    list = list.Where(c => c.FirstName == request.FirstName ).ToList();
                }
                if(request.Department != 0)
                {
                    list = list.Where(c => c.Department == request.Department).ToList();
                }
                if(request.EmploymentStatus!=0)
                {
                    list = list.Where(c => c.EmploymentStatus == request.EmploymentStatus).ToList();
                }
                result.totalCount = list.Count();
                result.totalPage = (int)Math.Ceiling(list.Count() / (double)request.pageSize);
                list = list.Skip((request.pageIndex - 1) * request.pageSize).Take(request.pageSize).ToList();
                if(list.Count>0)
                {
                    result.Messege = "获取数据成功";
                    result.Data = list;
                }
                else
                {
                    result.Code = (int)CodeEnum.search;
                    result.Messege = "没有数据";
                }

               
            }
            catch (Exception)
            {
                result.Messege = "数据出错";
                throw;
            }
            return result;
        }
    }
}
